var express = require('express');
var router = express.Router();

var db = require('../sqldb/index.js');
var email =require('../model/email.js')
var putEmail = require('../tools/putEmail.js')
var getTime = require('../tools/getTime.js')

/* GET home page. */
router.post('/', function(req, res, next) {
	console.log(req.body)
	putEmail(req.body)
	.then((data) => {
		if (data.status==1) {
			console.log("发送成功");
			let sqlto=String(req.body.to).slice(1,String(req.body.to).length-1)
			sqlto=sqlto.replace("','",',')
			// console.log(req.headers.origin)
			let sql = {
				to: sqlto,
				title:req.body.title,
				content:req.body.content,
				time: getTime(),
				url: req.headers.origin
			}
			createSql(sql)
			.then((result)=>{

			})
			res.json({
				status:1,
				msg:'',
				result:data.result
			})
		}else{
			res.json({
				status:0,
				msg:data.msg,
				result:"发送失败"
			})
		}
	})
	
});


function createSql(data){
	return new Promise((resolve,reject) => {
		db.sequelize.transaction(function(t){
			console.log("+++++++++++++++++++")
			return email(db.sequelize).create(data,{
				transaction:t
			}).then(function(data){
				resolve(data)
			}).catch(function(err){
				console.log("发生错误：" + err);
			});
		})
	})
	
}

module.exports = router;
